from openpyxl import load_workbook
from openpyxl import Workbook
from openpyxl.worksheet.worksheet import Worksheet
import os.path as path


def load(file: str) -> Workbook:
    return load_workbook(file)


class ExcelFile:

    __EXCEL_FILES_DIR_NAME = 'excel_files'

    __slots__ = [
        'workbook'
    ]

    def __init__(self, file: str):
        self.workbook = load(self.handle_file_path(file))

    def handle_file_path(self, filename: str, raise_error: bool = True) -> str:
        file_path = filename if path.isabs(filename) else path.join(
            path.dirname(__file__),
            '..',
            self.__EXCEL_FILES_DIR_NAME, filename
        )
        if raise_error and not path.isfile(file_path):
            raise FileNotFoundError('文件<%s>不存在' % file_path)
        return file_path

    def get_sheet(self, sheet_name: str) -> Worksheet:
        return self.workbook[sheet_name]

    def save(self, filename: str) -> None:
        self.workbook.save(self.handle_file_path(filename, False))

